﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class UIMatch : UIBase
{
    public Image imageIcon;
    public Button buttonClose;
    public Button buttonEnterRoom;
    public Button buttonRandomRoom;
    public Button buttonCreateRoom;
    public Button buttonStartBattle;
    public Button buttonExitRoom;
    public Text textCotent;
    public InputField textRoomId;
    private Sequence _sequence;
    private const int MaxRoomNum = 8;
    protected override void Awake()
    {
        base.Awake();
        buttonStartBattle.gameObject.SetActive(false);
        buttonExitRoom.gameObject.SetActive(false);

        //登录，进入旧的房间
        ReEnterRoom();
    }
    public override void OnButtonCloseClick()
    {
        base.OnButtonCloseClick();
        SceneMgr.Instance.LoadScene(SceneName.SceneLogin);
    }

    private const int CreateRoomId = -1;
    private const int RandomMatchRoomId = -2;
    private bool _isRoomHost = false;
    public void OnEnterRoom(Button button)
    {
        _isRoomHost = false;
        int roomId;
        string roomIdStr = textRoomId.text.Trim();
        if (string.IsNullOrEmpty(roomIdStr))
        {
            UITips.Instance.Show(XLocalization.Get("请输入房号"));
            return;
        }
        if (!int.TryParse(roomIdStr, out roomId))
        {
            UITips.Instance.Show(XLocalization.Get("非法房间号"));
            roomId = CreateRoomId;
        }

        var req = new match();
        req.side = 1;
        req.room_id = roomId;
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    public void OnCreateRoom(Button button)
    {
        _isRoomHost = true;
        int roomId = CreateRoomId;
        var req = new match();
        req.side = 1;//备用
        req.room_id = roomId;
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    public void OnRandomEnterRoom(Button button)
    {
        _isRoomHost = false;
        var req = new match();
        req.side = 1;//备用
        req.room_id = RandomMatchRoomId;
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    public void OnButtonCopyRoomClick()
    {
        string prefix = "我已经建好骰子房间，房号:";
        var ret = GUIUtility.systemCopyBuffer = prefix + textRoomId.text;
        if(string.IsNullOrEmpty(ret) || ret == prefix)
            UITips.Instance.Show("不支持拷贝或者房号出错");
        else
            UITips.Instance.Show("已拷贝进剪切板");
        Debug.Log("GUIUtility.systemCopyBuffer:" + ret);
    }

    public void PlayAni()
    {
        //播放动画
        Sequence s = DOTween.Sequence();
        s.Append(imageIcon.DOFillAmount(0, 1));
        s.SetLoops(-1, LoopType.Yoyo);
        _sequence = s;

        //隐藏按钮
        buttonClose.gameObject.SetActive(false);
        buttonEnterRoom.gameObject.SetActive(false);
        buttonRandomRoom.gameObject.SetActive(false);
        buttonCreateRoom.gameObject.SetActive(false);
        buttonStartBattle.gameObject.SetActive(true);
        buttonExitRoom.gameObject.SetActive(true);
    }


    public void OnStartBattle(Button button)
    {
        if (!_isRoomHost)
        {
            UITips.Instance.Show(XLocalization.Get("只有房主，才能开始战斗"));
            return;
        }
        WebSocketClient.Instance.SendMsgName(button, "startbattle");
    }

    public void OnExitRoom(Button button)
    {
        WebSocketClient.Instance.SendMsgName(button, "exitroom");
    }
    protected override void onVisible()
    {
        Facade.Instance.RegistNetEvent(nameof(notify_exitroom_rsp), OnHandleNotifyExitroomRsp);//php
        Facade.Instance.RegistNetEvent(nameof(notify_enterbattle_rsp), OnHandleNotifyEnterbattleRsp);//php
        Facade.Instance.RegistNetEvent(nameof(match_rsp), OnHandleMatchRsp);//php
        Facade.Instance.RegistNetEvent(nameof(notify_enterroom_rsp), OnHandleNotifyEnterroomRsp);//php
        Facade.Instance.RegistNetEvent(nameof(startbattle_rsp), OnHandleStartbattleRsp);//php
        Facade.Instance.RegistNetEvent(nameof(exitroom_rsp), OnHandleExitRoomRsp);//php
    }

    protected override void OnInvisible()
    {
        Facade.Instance.UnRegistNetEvent(nameof(notify_exitroom_rsp), OnHandleNotifyExitroomRsp);
        Facade.Instance.UnRegistNetEvent(nameof(notify_enterbattle_rsp), OnHandleNotifyEnterbattleRsp);
        Facade.Instance.UnRegistNetEvent(nameof(match_rsp), OnHandleMatchRsp);
        Facade.Instance.UnRegistNetEvent(nameof(notify_enterroom_rsp), OnHandleNotifyEnterroomRsp);
        Facade.Instance.UnRegistNetEvent(nameof(startbattle_rsp), OnHandleStartbattleRsp);
        Facade.Instance.UnRegistNetEvent(nameof(exitroom_rsp), OnHandleExitRoomRsp);
    }

    protected override void OnClose()
    {
        base.OnClose();
        _sequence?.Kill();
        _sequence = null;
        textCotent.text = XLocalization.Get("开始匹配");
        imageIcon.fillAmount = 1;

        buttonClose.gameObject.SetActive(true);
        buttonEnterRoom.gameObject.SetActive(true);
        buttonRandomRoom.gameObject.SetActive(true);
        buttonCreateRoom.gameObject.SetActive(true);
        buttonStartBattle.gameObject.SetActive(false);
        buttonExitRoom.gameObject.SetActive(false);
        textRoomId.text = "";
    }

    private void OnHandleMatchRsp(System.Object data)
    {
        var rsp = data as match_rsp;
        if (rsp.ret != NetErrorCode.None)
        {
            if(rsp.room_id == RandomMatchRoomId)
                UITips.Instance.Show("非常抱歉:" + rsp.reason);//没有空闲房间
            else
                UITips.Instance.Show("出错了:" + rsp.reason);
        }
        else
        {
            PlayAni();
            textRoomId.text = rsp.room_id.ToString();
        }
    }

    private void OnHandleNotifyEnterroomRsp(System.Object data)
    {
        var rsp = data as notify_enterroom_rsp;
        textCotent.text = XLocalization.Get("已匹配人数:") + rsp.num + "/" + MaxRoomNum;
    }

    private void OnHandleStartbattleRsp(System.Object data)
    {
        var rsp = data as startbattle_rsp;
        if (rsp.ret != NetErrorCode.None)
            UITips.Instance.Show("非常抱歉:" + rsp.reason);
    }

    private void OnHandleExitRoomRsp(System.Object data)
    {
        var rsp = data as exitroom_rsp;
        if (rsp.ret != NetErrorCode.None)
        {
            UITips.Instance.Show("出错了:" + rsp.reason);
            this.OnClose();//恢复状态
        }
        else
        {
            this.OnClose();//恢复状态
        }
    }

    private void OnHandleNotifyExitroomRsp(System.Object data)
    {
        var rsp = data as notify_exitroom_rsp;
        textCotent.text = XLocalization.Get("已匹配人数:") + rsp.num + "/" + MaxRoomNum;
    }

    private void OnHandleNotifyEnterbattleRsp(System.Object data)
    {
        var rsp = data as notify_enterbattle_rsp;
        Debug.Log("收到服务端的notify_enterbattle消息:" + rsp.persons.Length);
        this.CloseUI();

        //数据保存
        var dataBattle = new DataBattleMgr();
        for (int i = 0; i < rsp.persons.Length; i++)
        {
            var person = rsp.persons[i];
            dataBattle.AddDataPlayer(person);
        }

        SceneMgr.Instance.LoadScene(SceneName.SceneBattle, dataBattle);
    }

    //re enter room
    private void ReEnterRoom()
    {
        if(DataPlayer.Instance.cacheGroupId > 0)
        {
            UIDialog.Instance.Show(XLocalization.Get("提示"), XLocalization.Get("发现旧房间还有人，是否进去？"), () => {
                var req = new reenterroom();
                req.side = 1;//备用
                req.room_id = (int)DataPlayer.Instance.cacheGroupId;
                WebSocketClient.Instance.SendSerialize(req);
                DataPlayer.Instance.cacheGroupId = 0;
            }, () => {
                WebSocketClient.Instance.SendMsgName("unbindgroup");
                DataPlayer.Instance.cacheGroupId = 0;
            });
        }
    }
}
